﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QiBu.Api.Helper.Common
{
    /// <summary>
    /// Form登录验证
    /// </summary>
    /// <typeparam name="T">用户类型</typeparam>
    public class FormLoginHelper<T> where T : class
    {
        /// <summary>
        /// 设置用户信息
        /// </summary>
        /// <param name="user">用户</param>
        /// <param name="createPersistentCookie">是否长期保持cookie</param>
        public static void Set(T user, bool createPersistentCookie = false)
        {
            string strUser = JSONHelper.Encode<T>(user);
            System.Web.Security.FormsAuthentication.SetAuthCookie(strUser, createPersistentCookie);
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <returns>用户信息</returns>
        public static T Get()
        {
            string strUser = System.Web.HttpContext.Current.User.Identity.Name;
            return JSONHelper.Decode<T>(strUser);
        }

        /// <summary>
        /// 注销
        /// </summary>
        /// <param name="redirectUrl">注销后跳转的地址</param>
        /// <returns></returns>
        public static void Logout(string redirectUrl = "/user/login")
        {
            System.Web.Security.FormsAuthentication.SignOut();
            System.Web.HttpContext.Current.Response.Redirect(redirectUrl);
        }
    }
}
